/**
 * 
 */
package com.hand.cloud.b2b.taobao.impl;

import de.hybris.platform.core.Registry;
import de.hybris.platform.core.model.order.OrderModel;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hand.cloud.b2b.daos.EPOrderDAO;
import com.hand.cloud.b2b.daos.OrderDAO;
import com.hand.cloud.b2b.daos.TBTradeDAO;
import com.hand.cloud.b2b.model.EPOrderModel;
import com.hand.cloud.b2b.model.TB_TradeModel;
import com.hand.cloud.b2b.taobao.DefaultProperties;
import com.hand.cloud.b2b.taobao.TradeOperationService;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.Trade;
import com.taobao.api.internal.tmc.Message;
import com.taobao.api.internal.tmc.MessageHandler;
import com.taobao.api.internal.tmc.MessageStatus;
import com.taobao.api.internal.tmc.TmcClient;
import com.taobao.api.request.TradeCloseRequest;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.request.TradeMemoAddRequest;
import com.taobao.api.request.TradeMemoUpdateRequest;
import com.taobao.api.request.TradePostageUpdateRequest;
import com.taobao.api.request.TradeReceivetimeDelayRequest;
import com.taobao.api.request.TradeShippingaddressUpdateRequest;
import com.taobao.api.response.TradeCloseResponse;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.taobao.api.response.TradeMemoAddResponse;
import com.taobao.api.response.TradeMemoUpdateResponse;
import com.taobao.api.response.TradePostageUpdateResponse;
import com.taobao.api.response.TradeReceivetimeDelayResponse;
import com.taobao.api.response.TradeShippingaddressUpdateResponse;


/**
 * @author StephenWang
 * @Time Aug 15, 201411:03:17 AM
 */
@Service(value = "tradeCreationService")
public class DefaultTradeOperationService implements TradeOperationService
{
	public static Logger LOG = Logger.getLogger(DefaultTradeOperationService.class);

	@Autowired
	private TBTradeDAO tbTradeDAO;

	@Autowired
	private EPOrderDAO epOrderDAO;

	@Autowired
	private OrderDAO orderDAO;

	/**
	 * 创建Hybris订单信息
	 */
	@Override
	public void createOrder()
	{

		//		final TradeCreate create = new TradeCreate();
		//		create.execute();

		LOG.info("--------DefaultTradeCreationService---createOrder-------------");
		// 8797010573176
		final TB_TradeModel tradeModel = this.tbTradeDAO.getTradeByPK("8796093069176");
		final EPOrderModel epOrder = this.epOrderDAO.createEpOrder(tradeModel);
		System.out.println("epOrderPK:" + epOrder.getPk());

		final OrderModel orderModel = this.orderDAO.createOrder(epOrder);
		System.out.println("orderPK:" + orderModel.getPk());
		if (1 == 1)
		{
			return;
		}


		final TmcClient client = new TmcClient("ws://mc.api.tbsandbox.com/", DefaultProperties.appKey, DefaultProperties.appSecret,
				"default");

		final TaobaoClient tbClient = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
				DefaultProperties.appSecret);

		client.setMessageHandler(new MessageHandler()
		{
			public void onMessage(final Message message, final MessageStatus status)
			{
				try
				{
					System.out.println("receive a message!");
					createOrderByTrade(null);

					if (1 == 1)
					{
						return;
					}

					final String jsonMessage = message.getContent();
					final JSONObject jsonObject = new JSONObject(jsonMessage);
					// long tid = 192385102046705L;
					final long tid = jsonObject.getLong("tid");
					System.out.println("tid：" + tid);
					System.out.println(jsonMessage);
					System.out.println(message.getTopic());
					// 默认不抛出异常则认为消息处理成功

					// 创建明细
					createOrderDetails(tbClient, tid);
				}
				catch (final Exception e)
				{
					e.printStackTrace();
					status.fail();// 消息处理失败回滚，服务端需要重发
				}
			}
		});
		try
		{
			client.connect();
			final long min10 = 1000 * 30;
			Thread.sleep(min10);
		}
		catch (final Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 创建Hybris订单行信息
	 * 
	 * @param client
	 * @param tid
	 */
	private void createOrderDetails(final TaobaoClient client, final long tid)
	{

		LOG.info("--------DefaultTradeCreationService---createOrderDetails-------------");

		final TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
		req.setFields("seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type");
		req.setTid(tid);

		try
		{
			final TradeFullinfoGetResponse response = client.execute(req, DefaultProperties.sessionKey);
			System.out.println("getTrade:" + response.getBody());
			final Trade trade = response.getTrade();

			// 打印信息
			printTrade(trade);
			// 创建订单
			createOrderByTrade(null);
		}
		catch (final ApiException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 打印信息
	 * 
	 * @param trade
	 */
	private void printTrade(final Trade trade)
	{
		System.out.println("trade.getBuyerAlipayNo(): " + trade.getBuyerAlipayNo());
		System.out.println("trade.getDiscountFee(): " + trade.getDiscountFee());
		System.out.println("trade.getHasPostFee(): " + trade.getHasPostFee());
		System.out.println("trade.getInvoiceName(): " + trade.getInvoiceName());
		System.out.println("trade.getInvoiceType(): " + trade.getInvoiceType());
		System.out.println("trade.getPayment(): " + trade.getPayment());
		System.out.println("trade.getPointFee(): " + trade.getPointFee());
		System.out.println("trade.getPostFee(): " + trade.getPostFee());
		System.out.println("trade.getSellerCodFee(): " + trade.getSellerCodFee());
		System.out.println("trade.getSnapshotUrl(): " + trade.getSnapshotUrl());
		System.out.println("trade.getStatus(): " + trade.getStatus());
		System.out.println("trade.getTotalFee(): " + trade.getTotalFee());
		System.out.println("trade.getType(): " + trade.getType());

		for (final Order order : trade.getOrders())
		{
			System.out.println("order.getOuterIid():" + order.getOuterIid());
		}
	}

	/**
	 * 通过返回的数据创建Hybris订单
	 */
	private void createOrderByTrade(final Trade trade)
	{

		Registry.activateMasterTenant();

		// trade测试数据
		final Trade trade1 = initTrade();
		// 创建tbOrder
		final TB_TradeModel tbTrade = this.tbTradeDAO.createTBTrade(trade1);
		System.out.println("tbTradePK:" + tbTrade.getPk());

		final EPOrderModel epOrder = this.epOrderDAO.createEpOrder(tbTrade);
		System.out.println("epOrderPK:" + epOrder.getPk());

		final OrderModel orderModel = this.orderDAO.createOrder(epOrder);
		System.out.println("orderPK:" + orderModel.getPk());
	}

	/**
	 * @return
	 */
	public Trade initTrade()
	{
		final Trade trade = new Trade();
		final Order order = new Order();
		final List<Order> orders = new ArrayList<Order>();

		trade.setBuyerAlipayNo("tbtest1063");
		final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		final ParsePosition pos = new ParsePosition(0);
		final Date date = formatter.parse("2000-01-01 00:00:00", pos);
		trade.setCreated(date);
		trade.setDiscountFee("200.07");
		trade.setHasPostFee(true);
		trade.setInvoiceName("淘宝");
		trade.setInvoiceType("水果");
		trade.setPayment("200");
		trade.setPointFee((long) 0);
		trade.setPostFee("15");
		trade.setSellerCodFee("12.07");
		trade.setSnapshotUrl("T1mURbXopZXXXe3rL");
		trade.setStatus("TRADE_NO_CREATE_PAY");
		trade.setTotalFee("290");
		trade.setType("fixed");

		trade.setReceiverAddress("Pudong");
		trade.setReceiverCity("SH");
		trade.setReceiverDistrict("Pudong");
		trade.setReceiverMobile("111111111");
		trade.setReceiverName("Cynthia");
		trade.setReceiverPhone("12300000");
		trade.setReceiverState("SH");
		trade.setReceiverZip("210210");

		order.setNum((long) 30);
		order.setPrice("200");
		order.setTotalFee("6000");
		order.setItemMealName("M8原装电池");
		orders.add(order);
		trade.setOrders(orders);
		return trade;
	}

	/**
	 * 关闭交易
	 */
	@Override
	public void closeTrade(final Long tid, final String closeReason)
	{
		// YTODO Auto-generated method stub
		final TaobaoClient client = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
				DefaultProperties.appSecret);
		final TradeCloseRequest req = new TradeCloseRequest();
		req.setTid(tid);
		req.setCloseReason(closeReason);
		try
		{
			final TradeCloseResponse response = client.execute(req, DefaultProperties.sessionKey);
			System.out.println(response.getBody());
			System.out.println(response.getMsg());
		}
		catch (final ApiException e)
		{
			// YTODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 添加备注信息
	 */
	@Override
	public void addMemo(final Long tid, final String memo, final Long flag)
	{
		// YTODO Auto-generated method stub
		final TaobaoClient client = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
				DefaultProperties.appSecret);
		final TradeMemoAddRequest req = new TradeMemoAddRequest();
		req.setTid(tid);
		req.setMemo(memo);
		req.setFlag(flag);
		try
		{
			final TradeMemoAddResponse response = client.execute(req, DefaultProperties.sessionKey);
			System.out.println(response.getMsg());
			System.out.println(response.getTrade().getBuyerMemo());

		}
		catch (final ApiException e)
		{
			// YTODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 更新备注信息
	 */
	@Override
	public void updateMemo(final Long tid, final String memo, final Long flag, final Boolean reset)
	{
		// YTODO Auto-generated method stub
		final TaobaoClient client = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
				DefaultProperties.appSecret);
		final TradeMemoUpdateRequest req = new TradeMemoUpdateRequest();
		req.setTid(tid);
		req.setMemo(memo);
		req.setFlag(flag);
		req.setReset(reset);
		try
		{
			final TradeMemoUpdateResponse response = client.execute(req, DefaultProperties.sessionKey);
			System.out.println(response.getMsg());
			System.out.println(response.getTrade().getBuyerMemo());
		}
		catch (final ApiException e)
		{
			// YTODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 更新邮费
	 */
	@Override
	public void updatePostage(final Long tid, final String post_fee)
	{
		// YTODO Auto-generated method stub
		final TaobaoClient client = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
				DefaultProperties.appSecret);
		final TradePostageUpdateRequest req = new TradePostageUpdateRequest();
		req.setTid(tid);
		req.setPostFee(post_fee);
		try
		{
			final TradePostageUpdateResponse response = client.execute(req, DefaultProperties.sessionKey);
			System.out.println(response.getMsg());
		}
		catch (final ApiException e)
		{
			// YTODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 延迟交易的收货时间
	 */
	@Override
	public void delayReceivetime(final Long tid, final Long days)
	{
		// YTODO Auto-generated method stub
		final TaobaoClient client = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
				DefaultProperties.appSecret);
		final TradeReceivetimeDelayRequest req = new TradeReceivetimeDelayRequest();
		req.setTid(tid);
		req.setDays(days);
		try
		{
			final TradeReceivetimeDelayResponse response = client.execute(req, DefaultProperties.sessionKey);
			System.out.println(response.getMsg());
		}
		catch (final ApiException e)
		{
			// YTODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 更新收货地址
	 */
	@Override
	public void updateShippingAddress()
	{
		// YTODO Auto-generated method stub
		final TB_TradeModel tradeModel = this.tbTradeDAO.getTradeByPK("8797010573176");
		final TaobaoClient client = new DefaultTaobaoClient(DefaultProperties.serverUrl, DefaultProperties.appKey,
				DefaultProperties.appSecret);
		final TradeShippingaddressUpdateRequest req = new TradeShippingaddressUpdateRequest();
		req.setTid(tradeModel.getTid());
		req.setReceiverName(tradeModel.getReceiver_name());
		req.setReceiverPhone(tradeModel.getReceiver_phone());
		req.setReceiverMobile(tradeModel.getReceiver_mobile());
		req.setReceiverState(tradeModel.getReceiver_state());
		req.setReceiverCity(tradeModel.getReceiver_city());
		req.setReceiverDistrict(tradeModel.getReceiver_district());
		req.setReceiverAddress(tradeModel.getReceiver_address());
		req.setReceiverZip(tradeModel.getReceiver_zip());
		try
		{
			final TradeShippingaddressUpdateResponse response = client.execute(req, DefaultProperties.sessionKey);
			System.out.println(response.getMsg());
		}
		catch (final ApiException e)
		{
			// YTODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(final String[] args)
	{
		final DefaultTradeOperationService tradeOperation = new DefaultTradeOperationService();
		//		tradeOperation.updateShippingAddress();
		//itemOperation.createItem();

		//tradeOperation.closeTrade(192463696663100L, "不想买了");
		//tradeOperation.addMemo(192471768163100L, "Xueling:" + new Date(), 0L);
		//tradeOperation.updateMemo(192466758973100L, "麻烦发申通", 0L, false);
		//tradeOperation.updatePostage(192466758973100L, "3");
		//tradeOperation.delayReceivetime(192466758773100L, 3L);
		tradeOperation.updateShippingAddress();
	}

}
